package leetcode.q7;

/**
 * <a href="https://leetcode.cn/problems/reverse-integer/">...</a>
 * 7. 整数反转
 */
public class Solution {
    public int reverse(int x) {
        if (x == 0) { return x; }

        int n = x;
        x = Math.abs(x);
        String result = "";
        boolean flag = false;
        for (; x > 0; x /= 10) {
            int lsb = x % 10;
            if (lsb == 0 && flag) {
                result = result + lsb;
            }
            if (lsb != 0) {
                result = result + lsb;
                flag = true;
            }
        }

        if (n < 0) result = "-" + result;
        try {
            return Integer.parseInt(result);
        }catch (NumberFormatException e) {
            return 0;
        }
    }

    public static void printBin(int value) {
        for (int i = 31; i >= 0; i--) {
            System.out.print(((1 << i) & value) == 0 ? "0" : "1");
        }
        System.out.println();
    }

    public static int reverse2(int x) {
        if (x == 0) { return x; }

        int n = x;
        x = Math.abs(x);
        String result = "";
        for (; x > 0; x /= 10) {
            int lsb = x % 10;
            if (lsb != 0) result = result + lsb;
        }

        if (n < 0) result = "-" + result;
        try {
            return Integer.parseInt(result);
        }catch (NumberFormatException e) {
            return 0;
        }
    }

    public static void main(String[] args) {
        // printBin(256);
//        System.out.println(reverse2(123));
//        System.out.println(reverse2(-123));
//        System.out.println(reverse2(120));
//        System.out.println(reverse2(0));

        String value = "9646324351";
        System.out.println(Integer.parseInt(value));
    }
}